import React, { useState } from 'react';
import Alert from '@material-ui/lab/Alert';
import CircularProgress from '@material-ui/core/CircularProgress';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogActions from '@material-ui/core/DialogActions';
import Backdrop from '@material-ui/core/Backdrop';
import { makeStyles } from '@material-ui/core/styles';
import { useDebounce, ck_empty, cline, obj_int, obj_str_trim, IkInput, loc, NuiBt, uDb, useForm, obj_str } from 'sui';

const useStyles = makeStyles(theme => ({
    backdrop: {
        zIndex: theme.zIndex.drawer + 1,
        color: '#fff',
    },
}));

const Wait = ({ wait }) => {
    const classes = useStyles();

    return (
        <Backdrop className={classes.backdrop} open={wait}>
            <CircularProgress color="inherit" />
        </Backdrop>
    );
};

const NuiDlg = ({ open, hcmd, title, children, hcancel, labc=loc("base_36"), labk=loc("base_148"), labd=loc("nui_7"), width="sm"}) => {
    const hfunc = useDebounce(hcmd);

    const Cancel = () => {
        if (hcancel) {
            return (
                <div>
                    <NuiBt hcmd={hcancel} name="dlgcancel">{labc}</NuiBt>
                    <NuiBt className="ml-8 mr-4" hcmd={hfunc} name="dlgok">{labk}</NuiBt>
                </div>
            );
        }

        return <NuiBt hcmd={hfunc} name="dlgclose">{labd}</NuiBt>;
    };

    const hclose = (event, reason) => {
        if (reason === "backdropClick") {
            return;
        }

        hfunc();
    };

    return (
        <Dialog
            maxWidth={width}
            keepMounted
            disableEscapeKeyDown
            fullWidth={true}
            onClose={hclose}
            open={open}>
            <DialogTitle>{title}</DialogTitle>
            <div className="ml-4">
                {children}
            </div>
            <DialogActions>
                <Cancel/>
            </DialogActions>
        </Dialog>
    );
};

const BaseDlg = ({ open, title, hcmd, children, width="sm" }) => {
    const hfunc = useDebounce(hcmd);

    const hclose = (event, reason) => {
        if (reason === "backdropClick") {
            return;
        }

        hfunc();
    };

    return (
        <Dialog
            maxWidth={width}
            keepMounted
            disableEscapeKeyDown
            fullWidth={true}
            onClose={hclose}
            open={open}>
            <DialogTitle>{title}</DialogTitle>
            {children}
        </Dialog>
    );
};

const ErrView = ({ err, tp="error" }) => {
    if (err) {
        return <Alert severity={tp} className="my-4 text-2xl">{err}</Alert>;
    }

    return null;
};

const Info = ({ msg }) => <Alert severity="info" className="text-1xl my-4">{msg}</Alert>;

const CkUsn = ({ open, setOpen, hcmd, level=3 }) => {
    const [err, setErr] = useState(null);
    const [value, setValue] = useState();
    const form = useForm(setValue);

    const hdone = () => {
        const ck = {
            user: (v) => ck_empty(v),
            passwd: (v) => ck_empty(v),
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        uDb(null, "user/login",
            {
                line: cline(),
                sn: obj_str(value, "user"),
                passwd: obj_str(value, "passwd"),
            },
            r => {
                const sn = obj_str_trim(r, "sn");
                const auth = obj_int(r, "auth");
                if (sn !== "admin" && auth < level) {
                    setErr(loc("l_847"));
                    return;
                }

                form.hclear();
                setOpen(false);
                hcmd(sn);
            },
            e => setErr(loc("l_458"))
        );
    };

    return (
        <NuiDlg open={open} title="验证" hcmd={hdone} labd="确定" hcancel={() => setOpen(false)}>
            <IkInput label="用户" form={form} value={value} name="user"/>
            <IkInput label="密码" form={form} value={value} name="passwd" type="password"/>
            <ErrView err={err}/>
        </NuiDlg>
    );
};

const UsnDlg = ({ open, setOpen, hcmd }) => {
    const [err, setErr] = useState(null);
    const [value, setValue] = useState();
    const form = useForm(setValue);

    const hdone = () => {
        const ck = {
            user: (v) => ck_empty(v),
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        uDb(null, "user/get",
            {
                line: cline(),
                k: obj_str(value, "user"),
            },
            r => {
                const sn = obj_str_trim(r, "sn");

                form.hclear();
                setOpen(false);

                hcmd(sn);
            },
            e => setErr("没有这个用户")
        );
    };

    return (
        <NuiDlg open={open} title="用户" hcmd={hdone} labd="确定" hcancel={() => setOpen(false)}>
            <IkInput label="用户" form={form} value={value} name="user"/>
            <ErrView err={err}/>
        </NuiDlg>
    );
};

export {UsnDlg, CkUsn, Info, ErrView, BaseDlg, NuiDlg, Wait};
